package com.zy.openchat.util

import android.os.Build
import android.view.View
import java.lang.System

object FastClickUtil {

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private const val MIN_CLICK_DELAY_TIME = 800

    private val clickMap by lazy { hashMapOf<Int, Triple<Int, Int, Long>>() }

    @JvmStatic
    fun isFastClick(view: View?): Boolean {
        return isFastClick(view,MIN_CLICK_DELAY_TIME)
    }

    fun isFastClick(view: View?, delayTime:Int): Boolean {
        if(view==null){
            return false
        }
        val viewId = view.getViewId()
        val t = clickMap[viewId]
        val times = 1
        val third = System.currentTimeMillis()
        if (times == 1) {
            if (t == null || (third - t.third >= delayTime)) {
                clickMap[viewId] = Triple(1, 1, third)
                return false
            }
        } else {
            if (t == null) {
                clickMap[viewId] = Triple(times, 1, third)
            } else {
                if (third - t.third >= delayTime) {
                    clickMap[viewId] = Triple(times, 1, third)
                } else {
                    val newT = t.copy(second = t.second + 1, third = third)
                    clickMap[viewId] = newT
                    if (newT.second != newT.first) {
                        //不做任何操作
                    } else {
                        clickMap.remove(viewId)
                        return false
                    }
                }
            }
        }
        return true
    }

    private fun View.getViewId(): Int {
        var id = id
        if (id == View.NO_ID) {
            id = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                View.generateViewId()
            } else {
                this.hashCode()
            }
        }

        return id
    }

}